import config from '@/config/config.js';
import clStorage from "@/utils/storage";
import {navigateToLogin} from "./filters";
export default {
  /** showToast
   * 由于微信环境先调用showToast后调用hideLoading会把toast关闭，所以此处在setTimeout里调用，保证一个事件循环中hideLoading先进行
   * 真机延时0即可，模拟器需要加长
   */
  toast(param) {
    setTimeout(() => {
      if (typeof param === 'string') {
        uni.showToast({
          title: param,
          duration: 3000,
          icon: 'none',
        });
      }
      if (typeof param === 'object') {
        uni.showToast({
          duration: 3000,
          icon: 'none',
          ...param,
        });
      }
    }, 10);
  },

  /**显示Loading */
  showLoading(data) {
    uni.showLoading({
      title: '加载中',
      ...data,
    });
  },

  /**隐藏loading */
  hideLoading() {
    uni.hideLoading();
  },

  /**反转时间戳 */
  getReverseTime() {
    const time = new Date().getTime();

    return {
      time,
      reversetime: time
        .toString()
        .split('')
        .reverse()
        .join(''),
    };
  },

  /**导航跳转时复杂参数先存到globalData里面 */
  setNavData(data) {
    getApp().globalData.navigateData = data;
  },

  /**导航跳转时从globalData取出复杂参数 */
  getNavData() {
    return getApp().globalData.navigateData;
  },

  /**身份证获取年龄 */
  getAgeByIDNumber(identityCard) {
    const len = (identityCard + '').length;
    if (len == 0) {
      return 0;
    } else {
      if (len != 15 && len != 18) {
        //身份证号不合法
        return 0;
      }
    }
    let strBirthday = '';
    if (len === 18) {
      // 从18位身份证号获取生日和性别代码
      strBirthday =
        identityCard.substr(6, 4) +
        '/' +
        identityCard.substr(10, 2) +
        '/' +
        identityCard.substr(12, 2);
    }
    if (len === 15) {
      strBirthday =
        '19' +
        identityCard.substr(6, 2) +
        '/' +
        identityCard.substr(8, 2) +
        '/' +
        identityCard.substr(10, 2);
    }
    // 时间字符串里必须/
    const birthDate = new Date(strBirthday);
    const nowDateTime = new Date();
    let age = nowDateTime.getFullYear() - birthDate.getFullYear();
    // 考虑月，天的因素，getMonth获取的是从0开始的，这里进行比较，不需要加1
    if (
      nowDateTime.getMonth() < birthDate.getMonth() ||
      (nowDateTime.getMonth() === birthDate.getMonth && nowDateTime.getDate() < birthDate.getDate())
    ) {
      age--;
    }

    return age;
  },

  /**手机号，姓名，身份证前端脱敏处理 */
  desensitizeInfo(msg, type = 'name') {
    let returnStr = '';

    switch (type) {
      case 'name':
        // eslint-disable-next-line no-case-declarations
        const firstWord = msg.substring(0, 1);
        // eslint-disable-next-line no-case-declarations
        const lastWord = msg.substring(msg.length - 1, msg.length);
        returnStr`${firstWord}*${msg.length >= 3 ? lastWord : ''}`;
        break;

      // 手机号 155****5555 前三后四
      case 'tel':
        returnStr = `${msg.substring(0, 3)}****${msg.substring(msg.length - 4, msg.length)}`;
        break;

      //身份证前六后四
      case 'idNum':
        returnStr = `${msg.substring(0, 6)}******${msg.substring(msg.length - 4, msg.length)}`;
        break;

      default:
        break;
    }

    return returnStr;
  },

  /**传入对象返回url参数 */
  getParam(data) {
    let url = '';
    for (const k in data) {
      let value = data[k] !== undefined ? data[k] : '';
      url += `&${k}=${value}`;
    }
    return url ? url.substring(1) : '';
  },

  /**将url和参数拼接成完整地址 */
  getUrl(url, data) {
    return (url +=
      (url.indexOf('?') < 0 ? '?' : url.indexOf('&') < 0 ? '&' : '') + this.getParam(data));
  },

  /**获取路由中某个参数值 */
  getQueryString(name, url) {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    const r = (url && url.split('?')[1].match(reg)) || window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  },

  /**生产唯一id */
  getUID() {
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
  },

  /**
   *
   * @param {跳转到其他页面} jumpObj
   *  {
        jumpUrl: '/pages/addcar/index',
        // 是否是tabBar
        isTabbar: false,
      }
   */
  jumpToOtherPage(jumpObj) {
    console.log(jumpObj.jumpUrl)
    if (jumpObj && jumpObj.isTabbar) {
      uni.switchTab({
        url: jumpObj.jumpUrl,
      });
    } else {
      uni.navigateTo({
        url: this.getUrl(jumpObj.jumpUrl, { ...jumpObj.data }),
      });
    }
  },
  jumpToHome(){
    this.jumpToOtherPage({
      jumpUrl: 'pages/tabbar/home/index',
      // 是否是tabBar
      isTabbar: true,
    });
  },
  // 跳转协议页面
  jumpToAgree(type, title) {
    this.jumpToOtherPage({
      jumpUrl: '/pages/cms/agree',
      // 是否是tabBar
      isTabbar: false,
      data: {
        type: type,
        title: title,
      },
    });
  },
  /**
   * 跳转到登录页面
   */
  navigateToLogin (type = "navigateTo") {
    /**
     * 此处进行条件编译判断
     * 微信小程序跳转到微信小程序登录页面
     * H5/App跳转到普通登录页面
     */
    // #ifdef MP-WEIXIN
    uni[type]({
      url: "/pages/passport/wechatMPLogin",
    });
    // #endif
    // #ifndef MP-WEIXIN
    uni[type]({
      url: "/pages/passport/login",
    });
    //  #endif
  },
  /**
   * 登录后跳转判断
   * 计算出当前router路径
   * 1.如果跳转的链接为登录页面或跳转的链接为空页面。则会重新跳转到首页
   * 2.都不满足返回跳转页面
   * @param type  'default' || 'wx'  //返回地址会做判断默认为default
   */

   whetherNavigate(type = "default") {
    let navigation = getCurrentPages()[getCurrentPages().length - (getCurrentPages().length ) ];
    if (getCurrentPages().length > 1) {
      console.log(navigation, getCurrentPages());
      if (navigation.route == "pages/passport/login") {
        navigationToBack(type);
      } else {
        if (!navigation.route || navigation.route == "undefined") {
          navigationToBack(type);
        } else {
          uni.navigateBack({
            delta: getCurrentPages().length-1,
          });
        }
      }
    } else {
      uni.switchTab({
        url: "/pages/tabbar/home/index",
      });
    }
  },


  tipsToLogin (type) {
    if (!this.isLogin()) {
      uni.showModal({
        title: "提示",
        content: "当前用户未登录是否登录？",
        confirmText: "确定",
        cancelText: "取消",
        confirmColor: '#1ABC9C',
        success: (res) => {
          if (res.confirm) {
            navigateToLogin();
          } else if (res.cancel) {
            if(type !== 'normal'){
              uni.navigateBack();
            }

          }
        },
      });
      return false;
    }
    return true;
  },

  navigationToBack(type) {
    if (type == "wx") {
      // console.log(getCurrentPages().length - 3)
      uni.navigateBack({
        delta: getCurrentPages().length,
      });
    } else {
      uni.switchTab({
        url: "/pages/tabbar/home/index",
      });
    }
  },


  getDaysBetween(dateString2) {
    // const  startDate = Date.parse(dateString1);
    const startDate = new Date();
    const endDate = Date.parse(dateString2);
    const days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
    return Math.floor(days);
  },

  /*判断服务商是否是微信*/
  isWx(provider) {
    return 'weixin' === provider;
  },

  /*判断服务商是否是头条*/
  isToutiao(provider) {
    return 'toutiao' === provider;
  },


  parseClient(provider){
    let cli = 0;
    if ('weixin' === provider){
      cli = 1;
    }else if('toutiao' === provider){
      cli = 2;
    }
    return cli;
  },

  phoneClick(num) {
    const phoneNum = num || '400-0371-298';
    uni.makePhoneCall({
      phoneNumber: phoneNum,
    });
  },



  getAppName(){
    uni.getSystemInfo({
      success: function (res) {
        console.log(res.platform);
        console.log(res.appName);
        return res.appName;
      }
    });
  },

  isDouyin(){
    // return "Douyin" == appName
    uni.getSystemInfo({
      success: function (res) {
        console.log(res.platform);
        console.log(res.appName);
        return "Douyin" == res.appName;
      }
    });
    return false
  },

  parseAppName(appName){
    if (appName == 'Douyin') {
      return '抖音';
    } else if (appName == 'douyin_lite') {
      return '抖音';
    } else if (appName == 'Toutiao') {
      return '头条';
    } else {
      return '';
    }
  },

  getDaysInMonth(year,month){
    month = parseInt(month,10); //parseInt(number,type)这个函数后面如果不跟第2个参数来表示进制的话，默认是10进制。
    var temp = new Date(year,month,0);
    return temp.getDate();
  },

  // 判断当前H5环境是不是云闪付小程序
  isInUpApp() {
    var agent = navigator.userAgent.toLowerCase();
    var isInsideWallet = ((new RegExp(/(com.unionpay.chsp)/).test(agent)) || (new RegExp(/(com.unionpay.mobilepay)/).test(agent)));
    return isInsideWallet;
  },
  /**
   * 判断是否登录
   */
  isLogin(){
    let token = clStorage.getAccessToken();
    return token ? true : false;
  },


  /**
   * 验证是否登录如果没登录则去登录
   * @param {*} val
   * @returns
   */

  forceLogin () {
    if (!this.isLogin()) {
      this.navigateToLogin()
    }
  },



  /**
   * 跳转im
   */
  talkIm (storeId, goodsId, id) {
    if (this.isLogin('auth')) {
      let url = `/pages/mine/im/index?userId=${storeId}`
      if(goodsId && id) url = `/pages/mine/im/index?userId=${storeId}&goodsid=${goodsId}&skuid=${id}`
      uni.navigateTo({
        url
      });
    }
    else {
      this.tipsToLogin()
    }
  },


  /**
   * 获取文件上传地址
   */
  getUploadUrl(){
    // #ifdef H5
      return  '/dev-api' + config.uploadUrl;
    // #endif
    // #ifndef H5
    return config.getEnvConfig().apiPrefix + config.uploadUrl;
    // #endif
  },
  /*选择图片封装*/
  sendChoosePic() {
    return new Promise((resolve, reject) => {
      // #ifdef MP-WEIXIN || MP-TOUTIAO ||  MP-ALIPAY
      uni.chooseImage({
        // count:  允许上传的照片数量
        count: 1,
        // sizeType:  //original 原图，compressed 压缩图，默认二者都有
        sizeType: 'compressed',
        success(res) {
          console.log('图片选择结果', JSON.stringify(res));
          uni.showLoading({
            title: '加载中',
          });
          let filepath = res.tempFilePaths[0];
          console.log("filePath:"+filepath)
          uni.getFileSystemManager().readFile({
            filePath: filepath,
            encoding: 'base64',
            success: res => {
              resolve({
                filePath: filepath,
                res: res
              });
            },
            fail: err => {
              reject(err);
            },
          });

        },
      });
      // #endif
      // #ifdef H5
      if (this.isInUpApp()){
        upsdk.pluginReady(function () {
          upsdk.chooseImage({
            // maxWidth:'400', //目标图片宽度, 默认500,可选
            // maxHeight: '400', //目标图片高度, 默认1000,可选
            sourceType: '3', //1|2|3, 仅允许拍照|仅允许从手机相册中选图|拍照或从手机相册中选图都支持, 默认为3’，可选
            success: function (data) {
              if (data.base64) {
                resolve({
                  filePath: 'data:image/jpeg;base64,' + data.base64,
                  res: {
                    data: data.base64
                  }
                });
              }
            },
            fail: err => {
              console.log(err)
              uni.showToast({
                title: '请先授权获取相机权限哦',
                duration: 3000,
                icon: 'none',
              });
            },
          })
        })
      }else{
        uni.chooseImage({
          // count:  允许上传的照片数量
          count: 1,
          // sizeType:  //original 原图，compressed 压缩图，默认二者都有
          sizeType: 'compressed',
          success(res) {
            console.log('图片选择结果', JSON.stringify(res));
            uni.showLoading({
              title: '加载中',
            });
            let filepath = res.tempFilePaths[0];
            console.log("filePath:"+filepath)
            uni.uploadFile({
              url: '/prod-api/api/open/ocr/vehicle',
              filePath: filepath,
              name: 'file',
              success: res => {
                console.log(1100000, res);
                uni.hideLoading();
                if (JSON.parse(res.data).code === 200) {
                  // 上传成功再显示图片
                  resolve({
                    filePath: filepath,
                    res: {
                      data: JSON.parse(res.data).data
                    },
                    isResult: true
                  });
                } else {
                      reject(res);
                }
              },
              fail: res => {
                console.log(res);
                uni.hideLoading();
                uni.showToast({
                  title: '图片上传失败',
                  duration: 3000,
                  icon: 'none',
                });
              },
            });
          },
        });
      }
      // #endif
    }).then(
      res => {
        uni.hideLoading();
        return Promise.resolve(res);
      },
      err => {
        uni.hideLoading();
        return Promise.reject(err);
      }
    );
  },


  /* 获取定位 */
  getLoc() {
    console.log("开始定位")
    // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-ALIPAY
    return  this.getLocation();
    // #endif
    // #ifdef H5
    if (this.isInUpApp()){
      console.log("云闪付环境")
     return  this.getUnionpayLoc();
    }else {
      console.log("普通H5环境")
      return this.getLocation();
    }
    // #endif
  },


  getLocation() {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'gcj02',
        success: function(res) {
          console.log('当前位置的经度：' + res.longitude);
          console.log('当前位置的纬度：' + res.latitude);

          resolve({
            lng: res.longitude,
            lat: res.latitude,
          })
        },
        fail: function(err) {
          console.log('当前位置定位失败:' + JSON.stringify(err));
          resolve({
            lng: config.defCoord.lng,
            lat: config.defCoord.lat,
          })
        }
      });
    });
  },

  getUnionpayLoc(){
    return new Promise((resolve, reject) => {
      upsdk.pluginReady(function() {
        upsdk.getLocationGps({
          success: function(data){
            console.log('定位    OK： ' + data)
            console.log('定位OK： ' + JSON.stringify(data))
            let coor = data;
            upsdk.getSystemInfo({
              success:function(res){
                // data={},具体属性见下表   Android  ios
                if ("Android" == res.platform){
                  coor = JSON.parse(data);
                }
                resolve({
                  lng: coor.longitude,
                  lat: coor.latitude,
                })
              }
            });

          },
          fail: function(data){
            // console.log('定位 fail ' + JSON.stringify(data))
            this.toast("请先授权获取位置信息,以获取更好的服务")
            resolve({
              lng: config.defCoord.lng,
              lat: config.defCoord.lat,
            })
          }
        });
      });
    });
  },
};
